<template>
  <div class="emoji-picker" v-if="visible">
    <div class="emoji-header">
      <h3>表情</h3>
      <button class="close-btn" @click="$emit('close')">×</button>
    </div>
    
    <!-- 搜索框 -->
    <div class="emoji-search">
      <input 
        type="text" 
        v-model="searchQuery" 
        class="search-input"
        placeholder="搜索表情..."
        @input="handleSearch"
      />
      <span class="search-icon">🔍</span>
    </div>
    
    <div class="emoji-tabs">
      <!-- 最近使用的表情标签 -->
      <div 
        class="emoji-tab"
        :class="{ active: activeCategory === -1 }"
        @click="activeCategory = -1"
      >
        ⏱️
      </div>
      
      <div 
        v-for="(category, index) in emojiCategories" 
        :key="index"
        class="emoji-tab"
        :class="{ active: activeCategory === index }"
        @click="activeCategory = index"
      >
        {{ category.icon }}
      </div>
    </div>
    
    <div class="emoji-content">
      <div class="emoji-grid">
        <div 
          v-for="(emoji, index) in currentEmojis" 
          :key="index"
          class="emoji-item"
          @click="selectEmoji(emoji)"
          :title="emoji.name"
        >
          {{ emoji.char }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'

// Props
const props = defineProps<{
  visible: boolean
}>()

// Emits
const emit = defineEmits<{
  (e: 'select', emoji: string): void
  (e: 'close'): void
}>()

// 响应式数据
const activeCategory = ref(-1) // 默认显示最近使用的表情
const searchQuery = ref('')
const recentEmojis = ref<Array<{char: string, name: string}>>([])
const MAX_RECENT_EMOJIS = 24

// 从localStorage加载最近使用的表情
const loadRecentEmojis = () => {
  try {
    const saved = localStorage.getItem('recent-emojis')
    if (saved) {
      recentEmojis.value = JSON.parse(saved)
    }
  } catch (e) {
    console.error('Failed to load recent emojis:', e)
  }
}

// 保存最近使用的表情到localStorage
const saveRecentEmojis = () => {
  try {
    localStorage.setItem('recent-emojis', JSON.stringify(recentEmojis.value))
  } catch (e) {
    console.error('Failed to save recent emojis:', e)
  }
}

// 添加表情到最近使用
const addToRecent = (emoji: {char: string, name: string}) => {
  // 移除已存在的相同表情（如果有）
  recentEmojis.value = recentEmojis.value.filter(item => item.char !== emoji.char)
  
  // 添加到开头
  recentEmojis.value.unshift(emoji)
  
  // 限制数量
  if (recentEmojis.value.length > MAX_RECENT_EMOJIS) {
    recentEmojis.value = recentEmojis.value.slice(0, MAX_RECENT_EMOJIS)
  }
  
  saveRecentEmojis()
}

// 处理搜索
const handleSearch = () => {
  if (searchQuery.value.trim()) {
    // 搜索时自动切换到搜索结果视图
    activeCategory.value = -2 // 特殊值表示搜索结果
  } else if (recentEmojis.value.length === 0) {
    // 无搜索内容且无最近使用表情时，显示第一个分类
    activeCategory.value = 0
  }
}

// 初始化时加载最近使用的表情
loadRecentEmojis()

// 表情分类和数据
const emojiCategories = [
  { name: '表情与情感', icon: '😊' },
  { name: '手与手势', icon: '👍' },
  { name: '自然', icon: '🌍' },
  { name: '食物', icon: '🍔' },
  { name: '活动', icon: '⚽' },
  { name: '物体', icon: '🚗' },
  { name: '符号', icon: '💯' }
]

// 各类表情数据
const emojiData = [
  // 表情与情感
  [
    { char: '😊', name: '微笑' },
    { char: '😂', name: '大笑' },
    { char: '😍', name: '爱心眼' },
    { char: '😎', name: '墨镜' },
    { char: '😢', name: '哭泣' },
    { char: '😡', name: '生气' },
    { char: '👍', name: '点赞' },
    { char: '❤️', name: '爱心' },
    { char: '🎉', name: '庆祝' },
    { char: '🙏', name: '祈祷' },
    { char: '👏', name: '鼓掌' },
    { char: '🙄', name: '翻白眼' },
    { char: '😴', name: '睡觉' },
    { char: '🤔', name: '思考' },
    { char: '😱', name: '惊讶' },
    { char: '😇', name: '天使' },
    { char: '🥰', name: '可爱' },
    { char: '😘', name: '飞吻' },
    { char: '🤗', name: '拥抱' },
    { char: '😋', name: '好吃' },
    { char: '🤩', name: '崇拜' },
    { char: '😅', name: '汗' },
    { char: '😉', name: '眨眼' },
    { char: '😁', name: '露齿笑' }
  ],
  // 手与手势
  [
    { char: '👋', name: '挥手' },
    { char: '✌️', name: '胜利' },
    { char: '🤞', name: '祈祷' },
    { char: '🤟', name: '我爱你' },
    { char: '👌', name: 'OK' },
    { char: '✊', name: '举拳' },
    { char: '👊', name: '拳头' },
    { char: '🤛', name: '左拳' },
    { char: '🤜', name: '右拳' },
    { char: '👐', name: '张开手' },
    { char: '🤲', name: '双手接' },
    { char: '🙌', name: '举手' },
    { char: '👏', name: '鼓掌' },
    { char: '🙏', name: '双手合十' },
    { char: '💪', name: '肌肉' },
    { char: '🤝', name: '握手' }
  ],
  // 自然
  [
    { char: '☀️', name: '太阳' },
    { char: '🌙', name: '月亮' },
    { char: '⭐', name: '星星' },
    { char: '🌈', name: '彩虹' },
    { char: '🌊', name: '波浪' },
    { char: '🌳', name: '树' },
    { char: '🌺', name: '花' },
    { char: '🌻', name: '向日葵' },
    { char: '🌿', name: '草' },
    { char: '🍃', name: '叶子' },
    { char: '🌍', name: '地球' },
    { char: '💧', name: '水滴' },
    { char: '🔥', name: '火' },
    { char: '❄️', name: '雪花' }
  ],
  // 食物
  [
    { char: '🍎', name: '苹果' },
    { char: '🍊', name: '橙子' },
    { char: '🍌', name: '香蕉' },
    { char: '🍓', name: '草莓' },
    { char: '🥑', name: '牛油果' },
    { char: '🥕', name: '胡萝卜' },
    { char: '🍔', name: '汉堡' },
    { char: '🍕', name: '披萨' },
    { char: '🌮', name: '塔可' },
    { char: '🍜', name: '面条' },
    { char: '☕', name: '咖啡' },
    { char: '🍵', name: '茶' },
    { char: '🍺', name: '啤酒' },
    { char: '🥤', name: '饮料' }
  ],
  // 活动
  [
    { char: '⚽', name: '足球' },
    { char: '🏀', name: '篮球' },
    { char: '🎾', name: '网球' },
    { char: '🎮', name: '游戏' },
    { char: '🎨', name: '艺术' },
    { char: '🎤', name: '麦克风' },
    { char: '🎸', name: '吉他' },
    { char: '🎹', name: '钢琴' },
    { char: '🎬', name: '电影' },
    { char: '📚', name: '书' }
  ],
  // 物体
  [
    { char: '🚗', name: '汽车' },
    { char: '🚲', name: '自行车' },
    { char: '✈️', name: '飞机' },
    { char: '🚆', name: '火车' },
    { char: '💻', name: '电脑' },
    { char: '📱', name: '手机' },
    { char: '📸', name: '相机' },
    { char: '⌚', name: '手表' },
    { char: '🎒', name: '背包' },
    { char: '🏠', name: '房子' },
    { char: '💡', name: '灯泡' },
    { char: '🔋', name: '电池' }
  ],
  // 符号
  [
    { char: '💯', name: '满分' },
    { char: '✨', name: '闪亮' },
    { char: '💫', name: '流星' },
    { char: '🌟', name: '闪亮星星' },
    { char: '💥', name: '爆炸' },
    { char: '🎉', name: '庆祝' },
    { char: '🎊', name: '派对' },
    { char: '🎁', name: '礼物' },
    { char: '🎈', name: '气球' },
    { char: '💌', name: '情书' },
    { char: '💘', name: '爱心箭' },
    { char: '💝', name: '爱心礼物' }
  ]
]

// 计算当前显示的表情
const currentEmojis = computed(() => {
  // 搜索结果
  if (activeCategory.value === -2 && searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase().trim()
    const results: Array<{char: string, name: string}> = []
    
    // 搜索所有分类的表情
    for (const category of emojiData) {
      for (const emoji of category) {
        if (emoji.name.toLowerCase().includes(query) && !results.find(r => r.char === emoji.char)) {
          results.push(emoji)
        }
      }
    }
    
    return results
  }
  
  // 最近使用的表情
  if (activeCategory.value === -1) {
    if (recentEmojis.value.length === 0 && !searchQuery.value.trim()) {
      // 无最近使用表情时，显示第一个分类
      activeCategory.value = 0
      return emojiData[0] || []
    }
    return recentEmojis.value
  }
  
  // 普通分类表情
  return emojiData[activeCategory.value] || []
})

// 选择表情
const selectEmoji = (emoji: { char: string; name: string }) => {
  // 添加到最近使用
  addToRecent(emoji)
  
  // 发送选择事件
  emit('select', emoji.char)
}
</script>

<style scoped>
.emoji-picker {
  position: absolute;
  bottom: 100%;
  left: 0;
  background: white;
  border-radius: 12px;
  box-shadow: 0 -2px 15px rgba(0, 0, 0, 0.15);
  width: 320px;
  max-height: 400px;
  display: flex;
  flex-direction: column;
  z-index: 1000;
  margin-bottom: 8px;
  animation: emojiPickerFadeIn 0.2s ease-out;
}

@keyframes emojiPickerFadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.emoji-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px 0;
}

.emoji-search {
  position: relative;
  margin: 8px 16px 12px;
}

.search-input {
  width: 100%;
  padding: 8px 32px 8px 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s;
}

.search-input:focus {
  border-color: #42b983;
}

.search-icon {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  pointer-events: none;
}

.emoji-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s;
}

.close-btn:hover {
  background-color: #f0f0f0;
  color: #333;
}

.emoji-tabs {
  display: flex;
  gap: 4px;
  padding: 8px 12px;
  border-bottom: 1px solid #eee;
  overflow-x: auto;
  scrollbar-width: none;
}

.emoji-tabs::-webkit-scrollbar {
  display: none;
}

.emoji-tab {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  cursor: pointer;
  border-radius: 6px;
  transition: background-color 0.2s;
  flex-shrink: 0;
}

.emoji-tab:hover {
  background-color: #f5f5f5;
}

.emoji-tab.active {
  background-color: #e8f5e9;
  color: #42b983;
}

.emoji-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.emoji-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 2px;
}

.emoji-item {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s;
  user-select: none;
  animation: emojiItemAppear 0.1s ease-out;
}

.emoji-item:hover {
  background-color: #f0f0f0;
  transform: scale(1.3);
  z-index: 1;
}

.emoji-item:active {
  transform: scale(1.1);
}

@keyframes emojiItemAppear {
  from {
    opacity: 0;
    transform: scale(0.8);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .emoji-picker {
    width: 280px;
    max-height: 360px;
  }
  
  .emoji-grid {
    grid-template-columns: repeat(7, 1fr);
  }
  
  .emoji-item {
    width: 28px;
    height: 28px;
    font-size: 18px;
  }
}

@media (max-width: 480px) {
  .emoji-picker {
    width: 240px;
    max-height: 280px;
  }
  
  .emoji-grid {
    grid-template-columns: repeat(6, 1fr);
  }
  
  .emoji-item {
    width: 26px;
    height: 26px;
    font-size: 16px;
  }
}
</style>